<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

/*
 * @author ThangTB
 * parser csv class
 * */
class CSVParser {

	function parserToEntity($iSymbolId, $filename) {
		$aData = $this -> parser($filename);
		return $this -> getSymbolData($aData, $iSymbolId);
	}

	function parserToEntity2($iSymbolId, $filename) {
		$aData = $this -> parser($filename);
		return $this -> getSymbolData2($aData, $iSymbolId);
	}

	/*
	 * parser csv from file to array
	 * */
	public function parser($filename) {
		$buf = file_get_contents($filename);
		$fp = tmpfile();
		fwrite($fp, $buf);
		rewind($fp);
		$h = 0;
		$csv_data = array();
		while (($data = fgetcsv($fp, 1000, ',')) !== FALSE) {
			for ($i = 0; $i < count($data); $i++) {
				$csv_data[$h][$i] = $data[$i];
			}
			$h++;
		}
		fclose($fp);
		return $csv_data;
	}

	/*
	 * get entity from array
	 * */
	public function getSymbolData($aData, $iSymbolId) {
		$aSymbolData = array();
		$index = 0;
        $count_aData = count($aData);
		for ($i = 0; $i < $count_aData; $i++) {
			if (count($aData[$i]) == 8) {
				if (trim($aData[$i][0]) != "Date") {
					$oSymbolData = new SymbolDataEntity();
					$oSymbolData -> setSymbolId($iSymbolId);
					$date = new DateTime($aData[$i][0]);
					$oSymbolData -> setDate($date -> format("Y-m-d"));
					$oSymbolData -> setOpenPrice($aData[$i][1]);
					$oSymbolData -> setHighPrice($aData[$i][2]);
					$oSymbolData -> setLowPrice($aData[$i][3]);
					$oSymbolData -> setLastTradedPrice($aData[$i][4]);
					$oSymbolData -> setClosePrice($aData[$i][5]);
					$aSymbolData[$index] = $oSymbolData;
					$index++;
				}
			}
		}
		return $aSymbolData;
	}

	/*
	 * get entity from array
	 * */
	public function getSymbolData2($aData, $iSymbolId) {
		$aSymbolData = array();
		$index = 0;
        $count_aData = count($aData);
		for ($i = 0; $i < $count_aData; $i++) {
			if (count($aData[$i]) == 7) {
				if (trim($aData[$i][0]) != "Date") {
					$oSymbolData = new SymbolDataEntity();
					$oSymbolData -> setSymbolId($iSymbolId);
					$date = new DateTime($aData[$i][0]);
					$oSymbolData -> setDate($date -> format("Y-m-d"));
					$oSymbolData -> setOpenPrice($aData[$i][1]);
					$oSymbolData -> setHighPrice($aData[$i][2]);
					$oSymbolData -> setLowPrice($aData[$i][3]);
					$oSymbolData -> setLastTradedPrice(0);
					$oSymbolData -> setClosePrice($aData[$i][4]);
					$aSymbolData[$index] = $oSymbolData;
					$index++;
				}
			}
		}
		return $aSymbolData;
	}

}
